<template>
  <v-container>
    <h1 class="text-h4 mb-4">运动库</h1>
    <p class="text-subtitle-1 mb-6 text-medium-emphasis">
      在这里发现、学习并探索适合你的训练动作。
    </p>

    <v-row class="mb-4">
      <v-col cols="12" md="3">
        <v-text-field
            v-model="filters.nameKeyword"
            label="搜索动作名称"
            prepend-inner-icon="mdi-magnify"
            variant="outlined"
            density="compact"
            clearable
            hide-details
            @update:model-value="debouncedFetchExercises"
            :disabled="loading"
        ></v-text-field>
      </v-col>
      <v-col cols="12" md="2">
        <v-select
            v-model="filters.bodyPart"
            :items="bodyPartOptions"
            label="身体部位"
            variant="outlined"
            density="compact"
            clearable
            hide-details
            @update:model-value="fetchExercises"
            :disabled="loading"
        ></v-select>
      </v-col>

      <v-col cols="12" md="2">
        <v-select
            v-model="filters.difficulty"
            :items="difficultyOptions"
            label="选择难度"
            variant="outlined"
            density="compact"
            clearable
            hide-details
            @update:model-value="fetchExercises"
            :disabled="loading"
        ></v-select>
      </v-col>

      <v-col cols="12" md="2">
        <v-select
            v-model="filters.exerciseType"
            :items="exerciseTypeOptions"
            label="运动类型"
            variant="outlined"
            density="compact"
            clearable
            hide-details
            @update:model-value="fetchExercises"
            :disabled="loading"
        ></v-select>
      </v-col>

      <v-col cols="12" md="3">
        <v-select
            v-model="filters.equipment"
            :items="equipmentOptions"
            label="器械需求"
            variant="outlined"
            density="compact"
            clearable
            hide-details
            @update:model-value="fetchExercises"
            :disabled="loading"
        ></v-select>
      </v-col>
    </v-row>

    <v-progress-linear indeterminate color="primary" v-if="loading"></v-progress-linear>

    <v-alert type="info" variant="tonal" v-if="!loading && exercises.length === 0">
      没有找到符合条件的运动。
    </v-alert>

    <v-row v-else>
      <v-col v-for="exercise in exercises" :key="exercise.id" cols="12" sm="6" md="4">
        <v-card class="d-flex flex-column" height="100%">
          <v-card-title class="font-weight-bold">{{ exercise.name }}</v-card-title>
          <v-card-subtitle>
            {{ `目标部位: ${exercise.bodyPart}` }}
          </v-card-subtitle>

          <v-card-text class="flex-grow-1">
            <v-chip size="small" class="mr-2" color="teal">{{ formatDifficulty(exercise.difficulty) }}</v-chip>
            <v-chip size="small" class="mr-2" color="blue">{{ formatExerciseType(exercise.exerciseType) }}</v-chip>
            <v-chip size="small" class="mr-2" color="grey">{{ formatEquipment(exercise.equipment) }}</v-chip>
          </v-card-text>

          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="primary" variant="tonal" @click="openDetailDialog(exercise)">
              查看详情
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>

    <div class="text-center mt-6" v-if="canLoadMore">
      <v-btn @click="loadMore" :loading="loadingMore" :disabled="loading" variant="tonal">加载更多</v-btn>
    </div>

    <v-dialog v-model="detailDialog.show" max-width="600px">
      <v-card v-if="detailDialog.selectedExercise">
        <v-card-title class="text-h5 pt-4">{{ detailDialog.selectedExercise.name }}</v-card-title>
        <v-card-subtitle>{{ `目标部位: ${detailDialog.selectedExercise.bodyPart}` }}</v-card-subtitle>

        <v-card-text>
          <v-chip size="small" class="my-3 mr-2" color="teal">
            {{ formatDifficulty(detailDialog.selectedExercise.difficulty) }}
          </v-chip>
          <v-chip size="small" class="my-3 mr-2" color="blue">
            {{ formatExerciseType(detailDialog.selectedExercise.exerciseType) }}
          </v-chip>
          <v-chip size="small" class="my-3 mr-2" color="grey">
            {{ formatEquipment(detailDialog.selectedExercise.equipment) }}
          </v-chip>

          <p class="body-1 my-4">
            {{ detailDialog.selectedExercise.description }}
          </p>

          <v-alert v-if="detailDialog.selectedExercise.recommendedSetsReps"
                   type="info"
                   variant="tonal"
                   density="compact"
                   class="my-4"
                   icon="mdi-weight-lifter"
          >
            <strong>推荐组数:</strong> {{ detailDialog.selectedExercise.recommendedSetsReps }}
          </v-alert>

          <v-alert v-if="detailDialog.selectedExercise.errorCues"
                   type="warning"
                   variant="tonal"
                   density="compact"
                   class="my-4"
                   icon="mdi-alert-circle-outline"
          >
            <strong>常见错误:</strong> {{ detailDialog.selectedExercise.errorCues }}
          </v-alert>

          <a :href="detailDialog.selectedExercise.videoUrl" target="_blank" rel="noopener noreferrer">
            <v-btn prepend-icon="mdi-television-play" color="red" variant="tonal">观看教学视频</v-btn>
          </a>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions class="pa-4">
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="detailDialog.show = false">关闭</v-btn>
          <v-btn color="primary" variant="flat" @click="addToTemplate" prepend-icon="mdi-plus-box">
            添加到模板
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </v-container>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import Request from '@/utils/Request';
import {debounce} from 'lodash-es';
import {useNotificationStore} from '@/stores/notification';

// --- 初始化 (保持不变) ---
const router = useRouter();
const notificationStore = useNotificationStore();

// --- 响应式状态 (保持不变) ---
const loading = ref(true);
const loadingMore = ref(false);
const exercises = ref([]);
const canLoadMore = ref(true);

// --- 【!! V4 升级：筛选条件 !!】 ---
const filters = reactive({
  nameKeyword: '',
  bodyPart: null,
  difficulty: null,     // <-- 【新】
  exerciseType: null,   // <-- 【新】
  equipment: null,      // <-- 【新】
  pageNumber: 1,
  pageSize: 10,
});

// [新增] 详情对话框的状态 (保持不变)
const detailDialog = reactive({
  show: false,
  selectedExercise: null,
});

// --- 【!! V4 升级：静态选项 !!】 ---
const bodyPartOptions = ['胸部', '背部', '腿部', '肩部', '手臂', '核心', '全身', '臀部'];

// (新) 难度选项 (注意 value 必须匹配 C# Enum)
const difficultyOptions = [
  {title: '零基础适配', value: 3}, // ZeroBasic = 3
  {title: '初级', value: 0},       // Beginner = 0
  {title: '中级', value: 1},       // Intermediate = 1
  {title: '高级', value: 2}        // Advanced = 2
];

// (新) 运动类型选项 (注意 value 必须匹配 C# Enum)
const exerciseTypeOptions = [
  {title: '力量训练', value: 0}, // Strength = 0
  {title: '有氧训练', value: 1}, // Cardio = 1
  {title: '拉伸放松', value: 2}  // Stretching = 2
];

// (新) 器械需求选项 (注意 value 必须匹配 C# Enum)
const equipmentOptions = [
  {title: '无器械', value: 0},   // NoEquipment = 0
  {title: '哑铃', value: 1},     // Dumbbell = 1
  {title: '弹力带', value: 2},   // ResistanceBand = 2
  {title: '健身房器械', value: 3} // GymEquipment = 3
];
// --- V4 升级结束 ---

// --- 核心API调用方法 ---
const fetchExercises = async (isLoadMore = false) => {
  if (!isLoadMore) {
    loading.value = true;
    filters.pageNumber = 1;
  } else {
    loadingMore.value = true;
  }
  try {
    const response = await Request.get('/exercises', filters);

    const newExercises = response.data;

    if (newExercises && newExercises.length > 0) {
      if (isLoadMore) {
        exercises.value.push(...newExercises);
      } else {
        exercises.value = newExercises;
      }
      canLoadMore.value = newExercises.length === filters.pageSize;
    } else {
      if (!isLoadMore) {
        exercises.value = [];
      }
      canLoadMore.value = false;
    }
  } catch (error) {
    // 错误通知已由您的 Request.js 拦截器自动处理
    console.error("获取运动列表失败 (已由拦截器处理):", error);
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// --- 事件处理 (保持不变) ---
const debouncedFetchExercises = debounce(() => fetchExercises(false), 500);

const loadMore = () => {
  filters.pageNumber++;
  fetchExercises(true);
};

// [新增] 打开详情对话框的方法
const openDetailDialog = (exercise) => {
  // 【!! V4 升级 !!】
  // C# API (ExerciseVo) 已被我们升级，
  // exercise 对象现在自动包含了 errorCues 和 recommendedSetsReps
  detailDialog.selectedExercise = exercise;
  detailDialog.show = true;
};

// [新增] 添加到模板的交互逻辑 (保持不变)
const addToTemplate = () => {
  const exercise = detailDialog.selectedExercise;
  if (!exercise) return;
  detailDialog.show = false;
  notificationStore.success(`即将跳转到模板编辑器添加 "${exercise.name}"`);
  router.push({
    name: 'TemplateEditorNew',
  });
};

// --- 【!! V4 升级：辅助函数 !!】 ---

// (已修复) 匹配 C# Enum
const formatDifficulty = (difficulty) => {
  const map = {0: '初级', 1: '中级', 2: '高级', 3: '零基础'};
  return map[difficulty] ?? '未知';
}

// (新)
const formatExerciseType = (type) => {
  const map = {0: '力量', 1: '有氧', 2: '拉伸'};
  return map[type] ?? '未知';
};

// (新)
const formatEquipment = (equip) => {
  const map = {0: '自重', 1: '哑铃', 2: '弹力带', 3: '器械'};
  return map[equip] ?? '自重';
};

// --- 生命周期钩子 ---
onMounted(fetchExercises);
</script>